<template>
  <div class="translate-wrap">
      <div class="filters">
        <div class="filter">
          <span>项目：</span>
          <el-select size="small" style="width: 150px;" v-model="queryParams.appid" @change="onAppchange">
            <el-option v-for="item in permission_projectList" :value="item.app_id" :label="item.name" :key="item.app_id"></el-option>
          </el-select>
        </div>
        <div class="filter">
          <span class="filter-item_label">渠道：</span>
          <span class="filter-item_opts">
            <select-check-box
              class="select-box"
              doubleColumn
              v-model="queryParams.unionid"
              :selOptions="channelOpts"
              checkAllLabel="全部渠道"
              filterable
              @change="reRender"
            />
          </span>
        </div>
        <div class="filter">
            <span class="filter-item_label">版本：</span>
            <span class="filter-item_opts">
              <version-select ref="versionSelect" :selOptions="versionOpts" isIntVer v-model="queryParams.version" @change="reRender"></version-select>
            </span>
          </div>
        <div class="filter">
          <span class="filter-item_label">选择日期：</span>
          <span class="filter-item_opts">
            <date-range
              :dateRange.sync="queryParams.time_range"
              @change="reRender"
            />
          </span>
        </div>
      </div>
      <div>
        <div v-for="(item, i) in metricsGroup" :key="i" v-loading="item.loading" class="charts-box">
          <el-button size="mini" type="primary" @click="exportCsv(item)">导出</el-button>
          <e-charts
            class="chart"
            :options="item.option"
            autoresize
          />
        </div>
      </div>
  </div>
</template>

<script type="text/javascript">
import { mapGetters } from 'vuex'
import DateRange from '../featReport/components/DateRange'
import ECharts from '@/components/Echarts/index'
import { getReportCfg, getMetricsGroup, getReportData, exportReportData } from '@/api/feedback/report'
import { parseTime } from '@/utils/index'
import { DATE_TYPE } from '../featReport/constant'
import * as echarts from 'echarts/core'
import { LineChart } from 'echarts/charts'
import { getChannelByAppId } from '@/api/system/channel'
import { getVersionTree } from '@/api'
echarts.use([LineChart])
const dateFmt = '{y}-{m}-{d}'
const indicatorMap = {}
// const indicatorMap = {
//   1: '安装人数',
//   2: '安装次数',
//   3: '日活',
//   4: '点击右上角按钮次数',
//   5: '点击右上角按钮人数',
//   6: '右上角入口翻译次数',
//   7: '右上角入口翻译人数',
//   8: '整页翻译次数',
//   9: '整页翻译人数',
//   10: '划词翻译次数',
//   11: '划词翻译人数',
//   15: '覆盖安装次数',
//   16: '覆盖安装人数',
//   17: '自动整页翻译次数',
//   18: '自动整页翻译人数',
//   19: '发音次数',
//   20: '发音人数',
//   21: '截图翻译人数',
//   22: '截图翻译次数',
//   101: '激活数'
// }
export default {
  name: 'Translate',
  components: {
    DateRange,
    ECharts
  },
  props: {},
  data () {
    const d = new Date()
    const end = parseTime(d, dateFmt)
    const start = parseTime(d.setDate(d.getDate() - 13), dateFmt)
    return {
      queryParams: {
        granularity: 'timestamp',
        version: [],
        unionid: [],
        time_range: [start, end],
        time_grain_sqla: DATE_TYPE.DAY,
        indicator: [],
        appid: null
      },
      // versionOpts: ['1.0.6', '1.0.7', '1.0.8', '1.0.9', '1.1.0'].map(v => ({
      //   value: v,
      //   label: `V${v}`
      // })),
      versionOpts: [],
      channelOpts: [],

      metricsGroup: []

      // loading1: false,
      // loading2: false,
      // loading3: false,
      // option1: {},
      // option2: {},
      // option3: {}
    }
  },
  created () {
    if (this.permission_projectList.length) {
      this.queryParams.appid = this.permission_projectList[0].app_id
    }

    this.init()
  },
  methods: {
    async init () {
      const bigID = await getReportCfg({
        appid: this.queryParams.appid,
        page: 'user_statistics'
      }).then(res => res.data.id)

      let metricsGroup = await getMetricsGroup(bigID).then(res => res.data)

      this.metricsGroup = metricsGroup.map(item => {
        return {
          loading: true,
          option: {},
          data_source: item.data_source,
          metrics: item.metrics.map(metrics => {
            indicatorMap[metrics.indicator] = metrics.label
            return metrics.indicator
          })
        }
      })
      getChannelByAppId({ app_ids: this.queryParams.appid }).then(res => {
        this.channelOpts = res.data.list.map(t => ({
          value: t.channel_id,
          label: `${t.name} (${t.channel_id})`
        }))
      })
      getVersionTree({ app_id: this.queryParams.appid, is_test: false }).then(res => {
        let list = res.data || []
        this.versionOpts = list
      })
      this.getData()
    },
    onAppchange () {
      this.queryParams.version = []
      this.queryParams.unionid = []
      this.queryParams.indicator = []
      this.init()
    },
    getData () {
      this.metricsGroup.forEach((item) => {
        const indicator = item.metrics
        const data_source = item.data_source
        item.loading = true
        this.getChartData({ ...this.queryParams, indicator, data_source })
          .then(res => {
            const list = (Array.isArray(res.data[0].result) && res.data[0].result[0].data) || []
            item.option = this.getOptions(list, indicator)
          })
          .finally(() => {
            item.loading = false
          })
      })
    },
    exportCsv (item) {
      if (item.dowmLoding) return
      const indicator = item.metrics
      const data_source = item.data_source
      item.downLoding = true
      exportReportData(this.getParameter({ ...this.queryParams, indicator, data_source })).then(res => {
        const href = URL.createObjectURL(res)
        const link = document.createElement('a')
        link.download = '翻译用户统计.csv'
        link.href = href
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        URL.revokeObjectURL(href)
      }).finally(() => {
        item.downLoding = false
      })
    },
    reRender () {
      this.getData()
    },
    getOptions (list, metrics) {
      const listMap = this.translateToMap(list)
      const xData = []
      const yData = metrics.map(val => ({
        name: indicatorMap[val],
        type: 'line',
        data: []
      }))
      const { time_range } = this.queryParams
      const st = new Date(time_range[0])
      st.setHours(8, 0, 0, 0)
      const et = new Date(time_range[1]).setHours(8, 0, 0, 0)
      while (Date.parse(st) <= et) {
        const obj = listMap[Date.parse(st)]
        xData.push(
          `${parseTime(st, dateFmt)}（${'日一二三四五六'.charAt(st.getDay())}）`
        )
        yData.forEach(it => {
          it.data.push({
            name: it.name,
            value: (obj && obj[it.name]) || 0
          })
        })
        st.setDate(st.getDate() + 1)
      }
      return {
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          type: 'scroll',
          bottom: 10
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: xData
        },
        yAxis: {
          type: 'value'
        },
        series: yData
      }
    },
    translateToMap (arr) {
      return arr.reduce((obj, t) => {
        const o = (obj[t.__timestamp] = {})
        for (const k in t) {
          if (k !== '__timestamp') {
            o[k] = t[k] || 0
          }
        }
        return obj
      }, {})
    },
    getParameter (params = {}) {
      const query = {}
      const length = this.versionOpts.reduce((num, item) => {
        num += item.versions.length
        return num
      }, 0)
      Object.keys(params).forEach(key => {
        let val = params[key]
        let flag = false
        if (key === 'version' && val.length === length) {
          return true
        }
        if (key === 'time_range') {
          val = `${val[0] + 'T00:00:00'} : ${val[1] + 'T23:59:59'}`
        } else if (Array.isArray(val)) {
          // 选项中存在只有一个空串的情况，需要传递到后端
          flag = val.length === 1 && val[0] === ''
          val = val.join(',')
        }
        if (['version', 'appid', 'unionid'].includes(key) && (val || flag)) {
          let filters = query.filters || ''
          if (filters) filters += ' and '
          filters += `${key} in (${val})`
          query.filters = filters
        } else if (val !== '') {
          query[key] = val
        }
      })
      return query
    },
    getChartData (params = {}) {
      return getReportData(this.getParameter(params))
    }
  },
  computed: {
    ...mapGetters('zcsd-core', ['permission_projectList'])
  }
}
</script>

<style lang="scss" scoped>
.translate-wrap {
  .el-card ::v-deep .el-card__body {
    display: flex;
    flex-direction: column;
    overflow: hidden;
  }
  .filters {
    display: flex;
    flex-wrap: wrap;

    .filter {
      display: flex;
      margin-right: 20px;
      align-items: center;

      &:last-of-type {
        margin-right: 0;
      }

      .label {
        margin-right: 8px;
      }
    }
  }
  .chart {
    flex: 1;
    width: 100%;
    height: 450px;
    margin-bottom: 20px;
  }
}
.charts-box{
  position: relative;
  .el-button{
    position: absolute;
    right: 10%;
    top: 10px;
    z-index: 3;
  }
}
</style>
